﻿using LPLS.Commons.DBModule;
using LPLS.Commons.Enums;
using LPLS.DBEntities;
using LPLS.DBEntities.ConfigModels.AlarmModels.AlarmVarableCodeRuleConfigModels;
using LPLS.DBEntities.ConfigModels.DeviceInfoModels;
using LPLS.DBEntities.OEEModule.OEEModels.DataStatisticModels;
using LPLS.DBInterface.ConfigModels.AlarmModel;
using LPLS.DBInterface.OEEModule.OEEModels.DataStaticsticModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LPLS.DBServices.OEEModule.OEEModels.DataStaticsticModels
{
    public class DeviceDataStatisticService : DBBaseService, IDeviceDataStatisticService
    {
        public DeviceDataStatisticService(DBContext dbContext) : base(dbContext)
        {
        }

        public List<DeviceDataStatistic> GetData()
        {
            var tempata = Client.Queryable<DeviceDataStatistic>().ToList();
            /// 切换数据库
            TempDataDeal(tempata);
            return tempata;

        }



        private void TempDataDeal(List<DeviceDataStatistic> tempata) 
        {
            ConfigTempDataBase(DatabaseEnum.SqliteConfig.ToString());
            var devicelist = TempClient.Queryable<DeviceBaseInfo>().ToList();
            Parallel.For(0, tempata.Count, i =>
            {
                var deviceStatusDesc = StatusEnumHelper.GetDescription(tempata[i].Status);
                tempata[i].DeviceName = devicelist.FirstOrDefault(x => x.ID == tempata[i].DeviceID)?.DeviceName ?? "未知设备";
                tempata[i].DeviceStatusDesc = deviceStatusDesc;
            });
        }

        public List<DeviceDataStatistic> GetData(Guid  deviceid)
        {
            var tempata = Client.Queryable<DeviceDataStatistic>().Where(e=>e.DeviceID==deviceid).OrderBy(s=>s.StartTime).ToList();
            /// 切换数据库
            TempDataDeal(tempata);
            return tempata;
        }

        public List<DeviceDataStatistic> GetDataByDataTime(DateTime starttime, DateTime endtime, Guid  deviceid)
        {
            var tempata = Client.Queryable<DeviceDataStatistic>().
                Where(e => e.DeviceID == deviceid&&e.StartTime>=starttime&&e.StartTime<=endtime).OrderBy(s => s.StartTime).ToList();
            /// 切换数据库
            TempDataDeal(tempata);
            return tempata;
        }

        public List<DeviceDataStatistic> GetDataByStatus(StatusEnum Status, Guid  deviceid, DateTime starttime, DateTime endtime)
        {
            var tempata = Client.Queryable<DeviceDataStatistic>().
                Where(e => e.DeviceID == deviceid && e.StartTime >= starttime && e.StartTime <= endtime&&e.Status==Status).OrderBy(s => s.StartTime).ToList();
            /// 切换数据库
            TempDataDeal(tempata);
            return tempata;
        }

        public override void InitDataBaseName()
        {
            DataBaseName = DatabaseEnum.CollectionDataResult.ToString();
        }
    }
}
